package dryven.persistence;

import java.lang.annotation.Annotation;

import javax.persistence.EntityManager;

import dryven.annotations.Connection;
import dryven.config.DatabaseConfiguration;
import dryven.config.DatabaseConfigurationSource;
import dryven.model.di.LocalThreadStorage;

public class EntityManagerUtil {
	private DatabaseConfigurationSource _dbCfgs;
	private LocalThreadStorage _storage;
	
	public EntityManagerUtil(DatabaseConfigurationSource dbCfgs,
			LocalThreadStorage storage) {
		super();
		_dbCfgs = dbCfgs;
		_storage = storage;
	}
	
	public EntityManager getEntityManagerForType(Class<?> type) {
		DatabaseConfiguration cfg = _dbCfgs.getDefaultDatabaseConfiguration();
		Annotation[] annotations = type.getDeclaredAnnotations();
		if(annotations!=null) {
			for (Annotation annotation : annotations) {
				if(annotation.annotationType().equals(Connection.class)) {
					String name = ((Connection)annotation).value();
					cfg = _dbCfgs.getDatabaseConfigurationByName(name);
					if(cfg==null) {
						throw new RuntimeException(String.format("No connection defined in configuration with name '%s'", name));
					}
					break;
				}
			}
		}
		PersistenceConnection conn = (PersistenceConnection) _storage.getAttribute(getPersistenceConnectionStorageKey(cfg));
		return conn.getEntityManager();
	}
	
	public static String getPersistenceConnectionStorageKey(DatabaseConfiguration cfg) {
		return PersistenceConnection.class.getName()+cfg.getConnectionName();
	}
	
}
